package admin.data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.CooperationModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class CooperationData {
	
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "cooperation_";

	private int limit = 20;

	private int page = 1;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public CooperationData() {
		try {
			ObjectifyService.register(CooperationModel.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}

	public ArrayList<CooperationModel> list() {
		ArrayList<CooperationModel> cooperations = new ArrayList<CooperationModel>();

		int start = (page - 1) * limit;
		Query<CooperationModel> q = ofy.query(CooperationModel.class).filter("created !=", null).order("-created").limit(limit).offset(start);
		for (CooperationModel cooperation : q) {
			cooperations.add(cooperation);
		}

		return cooperations;
	}
	
	public CooperationModel getCooperation(String id) {
		CooperationModel cooperation = new CooperationModel();
		if (cache != null && cache.containsKey(prefix + id)) {
			cooperation = (CooperationModel) cache.get(prefix + id);
		} else {
			try {
				cooperation = ofy.get(new Key<CooperationModel>(CooperationModel.class, id));
				cache.put(prefix + id, cooperation);
			} catch (Exception e) {
				cooperation = null;
			}
		}
		return cooperation;
	}
	
	public void insert(CooperationModel cooperation) {
		if (cache != null) {
			cache.put(prefix + cooperation.getId(), cooperation);
		}
		ofy.put(cooperation);
	}

	public void delete(CooperationModel cooperation) {
		if (cache != null && cache.containsKey(prefix + cooperation.getId())) {
			cache.remove(prefix + cooperation.getId());
		}

		ofy.delete(cooperation);
	}
}
